<template>
  <div class="courses-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>课程管理</span>
          <el-button
            v-if="userStore.isAdmin || userStore.isTeacher"
            type="primary"
            @click="handleCreate"
          >
            新增课程
          </el-button>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryForm" class="search-form" label-width="80px">
        <el-form-item label="学院">
          <el-select
            v-model="queryForm.collegeId"
            placeholder="请选择学院"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="college in collegeOptions"
              :key="college.id"
              :label="college.name"
              :value="college.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入课程名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-space>
        </el-form-item>
      </el-form>
      
      <!-- 课程表格 -->
      <el-table
        v-loading="loading"
        :data="courseList"
        border
        stripe
        size="small"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="课程名称" min-width="200" />
        <el-table-column prop="courseCode" label="课程码" width="120" />
        <el-table-column label="所属学院" width="150">
          <template #default="{ row }">
            {{ getCollegeName(row.collegeId) }}
          </template>
        </el-table-column>
        <el-table-column label="主讲教师" width="120">
          <template #default="{ row }">
            {{ getTeacherName(row.teacherId) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleView(row.id)"
            >
              查看
            </el-button>
            <el-button
              v-if="userStore.isAdmin || (userStore.isTeacher && canEdit(row))"
              link
              type="success"
              @click="handleViewStudents(row.id)"
            >
              选课学生
            </el-button>
            <el-button
              v-if="userStore.isAdmin || (userStore.isTeacher && canEdit(row))"
              link
              type="warning"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="userStore.isAdmin || (userStore.isTeacher && canEdit(row))"
              link
              type="danger"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 课程表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="courseFormRules"
        label-width="100px"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input
            v-model="courseForm.name"
            placeholder="请输入课程名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="课程码" prop="courseCode">
          <el-input
            v-model="courseForm.courseCode"
            placeholder="请输入课程码（唯一）"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="所属学院" prop="collegeId">
          <el-select
            v-model="courseForm.collegeId"
            placeholder="请选择学院"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="college in collegeOptions"
              :key="college.id"
              :label="college.name"
              :value="college.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主讲教师" prop="teacherId">
          <el-select
            v-model="courseForm.teacherId"
            placeholder="请选择主讲教师"
            filterable
            style="width: 100%"
            :disabled="!userStore.isAdmin"
          >
            <el-option
              v-for="teacher in teacherOptions"
              :key="teacher.id"
              :label="teacher.realName"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="课程详情"
      width="600px"
    >
      <el-descriptions :column="2" border v-if="viewCourse">
        <el-descriptions-item label="ID">{{ viewCourse.id }}</el-descriptions-item>
        <el-descriptions-item label="课程名称">{{ viewCourse.name }}</el-descriptions-item>
        <el-descriptions-item label="课程码">{{ viewCourse.courseCode }}</el-descriptions-item>
        <el-descriptions-item label="所属学院">
          {{ getCollegeName(viewCourse.collegeId) }}
        </el-descriptions-item>
        <el-descriptions-item label="主讲教师">
          {{ getTeacherName(viewCourse.teacherId) }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(viewCourse.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(viewCourse.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    
    <!-- 选课学生对话框 -->
    <el-dialog
      v-model="studentsDialogVisible"
      :title="`选课学生 - ${currentCourseName}`"
      width="900px"
    >
      <el-table
        v-loading="studentsLoading"
        :data="studentList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="{ row }">
            {{ row.sex || '未知' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phonenumber" label="手机号" width="120" />
        <el-table-column label="所属学院" width="150">
          <template #default="{ row }">
            {{ getCollegeName(row.collegeId) }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="studentsDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../store/user'
import { getCourseList, createCourse, updateCourse, deleteCourse, getCourseById, getCourseStudents, type UserInfo } from '../../api/course'
import { getAllColleges } from '../../api/college'
import { getUserList } from '../../api/user'

const userStore = useUserStore()

const loading = ref(false)
const submitLoading = ref(false)
const courseList = ref([])
const collegeOptions = ref([])
const teacherOptions = ref([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const studentsDialogVisible = ref(false)
const isEdit = ref(false)
const currentCourseId = ref(null)
const viewCourse = ref(null)
const currentCourseName = ref('')
const studentList = ref<UserInfo[]>([])
const studentsLoading = ref(false)

const queryForm = reactive({
  name: '',
  collegeId: null
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const courseFormRef = ref(null)
const courseForm = reactive({
  name: '',
  courseCode: '',
  collegeId: null,
  teacherId: null
})

const courseFormRules = {
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 100, message: '课程名称长度在2到100个字符', trigger: 'blur' }
  ],
  courseCode: [
    { required: true, message: '请输入课程码', trigger: 'blur' },
    { min: 2, max: 20, message: '课程码长度在2到20个字符', trigger: 'blur' }
  ],
  collegeId: [
    { required: true, message: '请选择所属学院', trigger: 'change' }
  ],
  teacherId: [
    { required: true, message: '请选择主讲教师', trigger: 'change' }
  ]
}

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑课程' : '新增课程'
})

// 判断是否可以编辑（教师只能编辑自己创建的课程）
const canEdit = (row: any) => {
  if (userStore.isAdmin) return true
  if (userStore.isTeacher) {
    const userId = parseInt(localStorage.getItem('userId') || '0')
    return row.teacherId === userId
  }
  return false
}

// 获取学院名称
const getCollegeName = (collegeId: number) => {
  const college = collegeOptions.value.find((c: any) => c.id === collegeId)
  return college ? college.name : '-'
}

// 获取教师名称
const getTeacherName = (teacherId: number) => {
  const teacher = teacherOptions.value.find((t: any) => t.id === teacherId)
  return teacher ? teacher.realName : '-'
}

// 加载学院列表
const loadColleges = async () => {
  try {
    const res = await getAllColleges()
    collegeOptions.value = res.data || []
  } catch (error) {
    ElMessage.error('获取学院列表失败')
  }
}

// 加载教师列表
const loadTeachers = async () => {
  try {
    const res = await getUserList({
      roleType: 'TEACHER',
      page: 1,
      size: 1000
    })
    teacherOptions.value = res.data.data || []
  } catch (error) {
    ElMessage.error('获取教师列表失败')
  }
}

// 获取课程列表
const fetchCourseList = async () => {
  loading.value = true
  try {
    const queryParams: any = {
      name: queryForm.name || undefined,
      collegeId: queryForm.collegeId || undefined,
      page: pagination.page,
      size: pagination.size
    }
    // 如果是教师，只查询自己的课程
    if (userStore.isTeacher && !userStore.isAdmin) {
      const userId = parseInt(localStorage.getItem('userId') || '0')
      queryParams.teacherId = userId
    }
    
    const res = await getCourseList(queryParams)
    
    // res 就是 ApiResponse，res.data 是 PageResult，res.data.data 是列表数据
    courseList.value = res.data.data || []
    pagination.total = res.data.total || 0
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  fetchCourseList()
}

// 重置
const handleReset = () => {
  queryForm.name = ''
  queryForm.collegeId = null
  handleQuery()
}

// 分页改变
const handlePageChange = (page: number) => {
  pagination.page = page
  fetchCourseList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchCourseList()
}

// 新增
const handleCreate = () => {
  isEdit.value = false
  currentCourseId.value = null
  resetCourseForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true
  currentCourseId.value = row.id
  Object.assign(courseForm, {
    name: row.name || '',
    courseCode: row.courseCode || '',
    collegeId: row.collegeId || null,
    teacherId: row.teacherId || null
  })
  dialogVisible.value = true
}

// 查看
const handleView = async (id: number) => {
  try {
    const res = await getCourseById(id)
    // res 就是 ApiResponse，res.data 是实际的课程对象
    viewCourse.value = res.data
    viewDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取课程详情失败')
  }
}

// 查看选课学生
const handleViewStudents = async (id: number) => {
  try {
    studentsLoading.value = true
    studentsDialogVisible.value = true
    
    // 获取课程信息以显示课程名称
    const courseRes = await getCourseById(id)
    if (courseRes.data) {
      currentCourseName.value = courseRes.data.name
    }
    
    // 获取选课学生列表
    const res = await getCourseStudents(id)
    studentList.value = res.data || []
    
    if (studentList.value.length === 0) {
      ElMessage.info('该课程暂无学生选课')
    }
  } catch (error) {
    ElMessage.error('获取选课学生列表失败')
  } finally {
    studentsLoading.value = false
  }
}

// 删除
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该课程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteCourse(id)
    ElMessage.success('删除成功')
    fetchCourseList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!courseFormRef.value) return
  
  await courseFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    submitLoading.value = true
    
    try {
      if (isEdit.value) {
        await updateCourse(currentCourseId.value, courseForm)
        ElMessage.success('更新成功')
      } else {
        // 如果是教师，自动设置teacherId为当前用户
        if (userStore.isTeacher && !userStore.isAdmin) {
          const userId = parseInt(localStorage.getItem('userId') || '0')
          courseForm.teacherId = userId
        }
        await createCourse(courseForm)
        ElMessage.success('创建成功')
      }
      
      dialogVisible.value = false
      fetchCourseList()
    } catch (error) {
      // 错误已在拦截器中处理
    } finally {
      submitLoading.value = false
    }
  })
}

// 重置表单
const resetCourseForm = () => {
  Object.assign(courseForm, {
    name: '',
    courseCode: '',
    collegeId: null,
    teacherId: null
  })
  courseFormRef.value?.clearValidate()
}

// 关闭对话框
const handleDialogClose = () => {
  resetCourseForm()
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

onMounted(async () => {
  await loadColleges()
  if (userStore.isAdmin) {
    await loadTeachers()
  }
  fetchCourseList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  font-size: 16px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

